import React from 'react';
import { WeaCheckbox,WeaLocaleProvider,WeaTools } from 'ecCom';
import { Icon} from 'antd';
import './../../style/viewtree/viewTree';
import NewTag from '../tag/NewTag';
const getLabel = WeaLocaleProvider.getLabel;
//datas-列表数据 type-(要进行的操作 非必须 add新增 update更新 childs展开子节点 del删除)
//params-进行操作的数组  optkey-进行操作的主键 对应datas数组里的key 
export default class ViewTree extends React.Component{
  constructor(props){
    super(props)
    this.state={
      treedatas: this.props.datas,
      nocache:this.initCache(),
      treetype:this.props.treetype,
      iconArray:{1:{type:"play-circle",title:getLabel(1960,"进行中"),color:"#64BAFF",isicon:1},
                 2:{type:"check-circle",title:getLabel(23774,"已完成"),color:"#52c41a",isicon:1},
                 3:{type:"icon-coms-Reset",title:getLabel(1981,"已撤销"),color:"rgb(203, 205, 206)"},
                 4:{type:"icon-coms-overtime",title:getLabel(515068,"待确认"),color:"#eaa81c"},
                 5:{type:"icon-coms-Edition",title:getLabel(83221,"已拒绝"),color:"#d81d19"},
                 6:{type:"icon-coms-currency-Process",title:getLabel(19134,"审批中"),color:"rgb(241, 2, 46)"}
                }
    }
  }
  initCache(){
      if(this.props.nocache!=undefined){
        return this.props.nocache;
      }
      return true;
  }
  componentWillReceiveProps(newProps){
      let {datas,params,treetype} =newProps;
      if(!datas){
        datas = [];
      }
      if(this.props.locationkey!=newProps.locationkey && params){
        let type = params.opttype;
        let optkey = params.optkey; //当前更新的id
        if(type && type.length>0){
          if(type=="add" || type=="dialogAdd"){
            if(treetype && treetype.length>0 && datas && datas.length>0){  //分类视图时 判断是否重复添加id
              let isadd =true;
              for(let i=0;i<datas.length;i++){
                if(datas[i].key==optkey){
                  isadd =false;
                }
              }
              if(isadd){
                datas.unshift(params.datas[0]);
              }
            }else{
              datas.unshift(params.datas[0]);
            }
          }else if(type=="update" || type=="childs" || type=="del" || type=="addchild" || type=="updateperson" || type=="updateall"){
            this.resetTreeDatas(datas,optkey,type,params);
          }else if(type=="batchtag"){
            let _optkeys = params.optkeys;
            let _params = params;
            for(let i=0;i<_optkeys.length;i++){
              if(optkey==2){
                _params = {};
                _params.tags = params.tags[_optkeys[i]];
              }
              this.resetTreeDatas(datas,_optkeys[i],'update',_params);
            }
          }else if(type=="delsub"){//批量删除
            let _optkeys = params.delData;
            for(let i=0;i<_optkeys.length;i++){
              this.resetTreeDatas(datas,_optkeys[i],'del',params);
            }
          }
        }
      }
      this.setState({treedatas:datas,treetype:treetype});
  }

  render(){
    const {treedatas,treetype} = this.state;
    return(
       <div className={"wea-workrelate-viewtree "+(this.props.className?this.props.className:"")}>
          {
            (treetype && treetype.length>0)?this.createTypeTree(treedatas,treetype):this.createTree(treedatas)
          }
       </div>
    )
  }

  /**
   * 创建树
   */
  createTree(treedatas,ischild){
    return (
      treedatas && treedatas.length > 0 && treedatas.map((element,idx)=>{
        return (
            <div className={"treenode"+this.getTreeClass(element)}>{this.getTreeIcon(element)}
              <div className="treecontent" onClick={(e) => this.nodeClick(e,element)}>
                 {this.getTreeIcon1(element,idx+1,idx,ischild)}
                 <div className="treecontent-title-div">
                    <div className={element.titleclass?element.titleclass+" treecontent-title":"treecontent-title"} title={element.title}>{element.title}</div>
                    {element.tags && element.tags.length>0 && <div className="treecontent-newtag"><NewTag ecId={`${this && this.props && this.props.ecId || ''}_NewTag@2fqzei@${element.key}`} linkdatas={element.tags} onLinkClose={(_v)=>this.onLinkClose(_v,element)}/></div>}
                 </div>
                 <div className="treecontent-btns" id={`treecontent-btns-${this.props.isSubTree ? "sub" : ""}${element.key}`} onClick={e => this.stopClickPropagation(e)}>{this.getComsBtn(element)}</div>
                 {this.getRightDatas(element.rightData,element.key)}
              </div>
              {element.isopen && this.createTree(element.childs,1)}
            </div>
        )
      })
    )
  }
  //根据数据类型从treedatas里面取出treetype一样的数据
  createTypeTree(treedatas,treetype){
    let num = 0;
    return (
      treedatas && treedatas.length > 0 && treedatas.map((element,idx)=>{
        if(element.treetype ==treetype){
          num++;
          return (
            <div className={"treenode"+this.getTreeClass(element)}>{this.getTreeIcon(element)}
              <div className="treecontent" onClick={(e) => this.nodeClick(e,element)}>
                 {this.getTreeIcon1(element,num,idx)}
                 <div className="treecontent-title-div">
                    <div className={element.titleclass?element.titleclass+" treecontent-title":"treecontent-title"} title={element.title}>{element.title}</div>
                    {element.tags && element.tags.length>0 && <div className="treecontent-newtag"><NewTag ecId={`${this && this.props && this.props.ecId || ''}_NewTag@bz3j32`} linkdatas={element.tags} onLinkClose={(_v)=>this.onLinkClose(_v,element)}/></div>}
                 </div>
                 <div className="treecontent-btns">{this.getComsBtn(element)}</div>
                 {this.getRightDatas(element.rightData,element.key)}
              </div>
              {element.isopen && this.createTree(element.childs)}
            </div>
        )
        }else{
          return "";
        }
      })
    )
  }
  /**
   * 生成右侧展示信息
   */
  getRightDatas(rightData,key){
    return (
      rightData && rightData.length > 0 && rightData.map((element,idx)=>{
        return element.name?<div className={element.classname?element.classname+" contentright":"contentright"} title={element.name}>{element.name}</div>:""
      }) 
    )
  }
  /**
   * 生成右侧btn组件
   * comsbtn--右侧按钮集合  key-主键id  otherInfo--其他信息
   */
  getComsBtn(p_element){
    let comsbtn = p_element.comsbtn;
    let key = p_element.key;
    let otherInfo = p_element.otherInfo;
    return (
      comsbtn && comsbtn.length > 0 && comsbtn.map((element,idx)=>{
        return (
          <div className="treebtn" onClick={(e) => this.comClick(e,element,key,comsbtn,otherInfo,p_element.tags)} title={element.title?element.title:""}>
          <div>{element.icon?<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@o4utm1@${element.type}`} type={element.icon} style={{paddingRight: "5px"}}/>:element.iicon?<i className={element.iicon} style={{paddingRight: "5px"}}/>:""}{element.com}</div></div>
        )
      })
    )
  }
  /**
   * 右侧btn组件点击事件
   */
  comClick(e,element,key,comsbtn,otherInfo,tags){
    if(typeof this.props.onRightBtnClick === "function"){
      this.props.onRightBtnClick(key,element,comsbtn,otherInfo,tags);
    }else{
      console.log("id",key);
    }
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }

  /**
   * 获取树的class
   */
  getTreeClass(element){
    var classname = "";
    if(element.childcount && element.childcount > 0){
      classname = " treeparent";
    }
    if(element.isopen){
      classname += " parentopen";
    }
    return classname;
  }

  /**
   * 获取树的箭头图标
   */
  getTreeIcon(element){
    if(element.childcount && element.childcount > 0){
      if(element.isopen){
        return <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@y435ws`} type="down" style={{position:'relative',zIndex:3,color:'grey'}} onClick={(e) => this.iconClick(e,element,1)} />;
      }
      return <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@lzg3ei`} type="right" style={{position:'relative',zIndex:3,color:'grey'}} onClick={(e) => this.iconClick(e,element,2)} />
    }
    return "";
  }
  /**
   * 获取列表的图标
   */
  getTreeIcon1(element,num,idx,ischild){
      let {boxProp} = this.props;
      let {iconArray} = this.state;
      let _viewAttr = "2";
      if(!element.candelete && boxProp==1){
        _viewAttr = "1";
      }
      let _numspan = <span className="treecontent-num">{num}</span>;
      let _checkbox = <div onClick={(e)=>this.stopClickPropagation(e)} className="treecontent-checkboxdiv">
                       <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@8b9u6w`} value={_viewAttr=="1"?"0":element.ischeckbox} viewAttr={_viewAttr} onChange={(v)=>this.checkBoxChange(element,v,idx,ischild)}/></div>;
      if(boxProp==0){
        _checkbox = "";
      }
      let iconobj = iconArray[element.status];
      if(iconobj){
        if(iconobj.isicon && iconobj.isicon==1){
          return <span className="treecontent-left-span">{_checkbox}{_numspan}<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@23bq7t`} type={iconobj.type} style={{position:'relative',zIndex:3,color:`${iconobj.color}`,margin:"0 10px 0 5px"}} theme="twoTone" twoToneColor="#64BAFF" title={iconobj.title}/></span>;
        }else{
          return <span className="treecontent-left-span">{_checkbox}{_numspan}<i className={iconobj.type} style={{position:'relative',zIndex:3,color:`${iconobj.color}`,margin:"0 10px 0 5px"}} title={iconobj.title}/></span>;
        }
      }
      // if(element.status==1){
      //   return <span className="treecontent-left-span">{_checkbox}{_numspan}<Icon type={iconArray[element.status]} style={{position:'relative',zIndex:3,color:"#64BAFF",margin:"0 10px 0 5px"}} theme="twoTone" twoToneColor="#64BAFF" title={getLabel(1960,"进行中")}/></span>;
      // }else if(element.status==2){
      //   return <span className="treecontent-left-span">{_checkbox}{_numspan}<Icon type="check-circle" style={{position:'relative',zIndex:3,color:"#52c41a",margin:"0 10px 0 5px"}} theme="twoTone" twoToneColor="#52c41a" title={getLabel(23774,"已完成")}/></span>;
      // }else if(element.status==3){
      //   return <span className="treecontent-left-span">{_checkbox}{_numspan}<i className={iconArray[element.status]} style={{position:'relative',zIndex:3,color:"rgb(203, 205, 206)",margin:"0 10px 0 5px"}} theme="twoTone" twoToneColor="#52c41a" title={getLabel(1981,"已撤销")}/></span>;
      // }
    return "";
  }
  /**
   * 树节点点击事件
   */
  nodeClick(e,element){
    if(typeof this.props.onTreeNodeClick === "function"){
      let {treedatas} = this.state;
      if(element.firstview){
        let _rData = element.rightData;
        if(element.rightData && element.rightData.length>0){
          element.rightData.map((_data,idx)=>{
            if(_data.classname=="fb_count_new"){
              _rData[idx].classname = "";
            }
          })
        }
        this.resetTreeDatas(treedatas,element.key,"update",{titleclass:'',rightData:_rData});
      }
      this.props.onTreeNodeClick(element.key,element.firstview);
    }else{
      console.log(element.key);
    }
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }

  /**
   * 树节点图标点击事件
   */
  iconClick(e,element,type){
    let {treedatas,nocache} = this.state;
    if(type==1){
      this.resetTreeDatas(treedatas,element.key,"childs");
      this.setState({"treedatas":treedatas});
    }else{
      if(nocache && element.childs && element.childs.length>0){
        this.resetTreeDatas(treedatas,element.key,"childs");
        this.setState({"treedatas":treedatas});
      }else{
        if(typeof this.props.onIconClick === "function"){
          this.props.onIconClick(element.key);
        }else{
          console.log(element.key);
        }
      }
    }
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }
  /**
   * 阻止事件冒泡
   */
  stopClickPropagation(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }
  /**
   * 复选框点击事件
   */
  checkBoxChange(element,v,idx,ischild){
    let {treedatas} = this.state;
    if(ischild && ischild==1){
      let optparams = {};
      optparams.optkey = element.key;
      optparams.ischeckbox = v;
      this.resetTreeDatas(treedatas,element.key,"update",optparams)
    }else{
      treedatas[idx].ischeckbox = v;
    }
    this.setState({treedatas:treedatas});
    if(typeof this.props.onOtherClick === "function"){
       this.props.onOtherClick(element.key,v,'checkbox');
    }
  }
  //标签删除事件
  onLinkClose(_v,element){
    let _id = element.key;
    let {treedatas} = this.state;
    let optparams = {};
    optparams.optkey = _id;
    optparams.tags = element.tags.filter((d, i) => d.id != _v);
    this.resetTreeDatas(treedatas,_id,"update",optparams)
    if(typeof this.props.onOtherClick === "function"){
      this.props.onOtherClick(_id,_v,'deltag',element);
    }
  }
  /**
   * 重置树节点数据
   */
  resetTreeDatas(treedatas,key,type,paramsdatas,pelement){
    if(treedatas && treedatas.length > 0){
      for(let n=0;n<treedatas.length;n++){
          let element = treedatas[n];
          if(element.key == key){
            if(type=="update"){//更新
              for(var i in paramsdatas){
                if(i in element){
                  element[i] = paramsdatas[i];
                }
              }
            }else if(type=="del"){//删除
              if(pelement && pelement.key){
                let childs = pelement.childs;
                let arridx = -1;
                for(let i=0;i<childs.length;i++){
                    if(childs[i].key==element.key){
                        arridx = i ;
                    }
                }
                if(arridx!=-1){
                    childs.splice(arridx,1);
                }
                pelement.childs = childs
                if( pelement.childs && pelement.childs.length==0){
                    pelement.childcount = 0;
                    pelement.isopen = false;
                }
              }else{
                treedatas.remove(element);
              }
            }else if(type=="childs"){ //展开子节点
              element.isopen = !element.isopen;
              if(paramsdatas && paramsdatas.datas.length>0){
                element.childs = paramsdatas.datas;
              }
            }else if(type=="addchild"){//树视图下新增子任务
              if(element.isopen){
                element.childs.push(paramsdatas.datas[0]);
                element.childcount = element.childcount+1;
              }else{
                if(element.childcount==undefined || element.childcount==0){
                  element.childcount = 1;
                  element.isopen = true;
                  element.childs = [];
                  element.childs.push(paramsdatas.datas[0]);
                }else{
                  element.childcount = element.childcount+1;
                }
              }
            }else if(type=="updateperson"){
              if(element.rightData && element.rightData.length>0){
                for(let i=0;i<element.rightData.length;i++){
                  if(element.rightData[i].id && element.rightData[i].id=="hrmid"){
                    element.rightData[i].name = paramsdatas.personname;
                  }
                }
              }
            }else if(type=="updateall"){
              WeaTools.callApi(paramsdatas.url, 'GET', paramsdatas.newparams).then((data) => {
                if (data.status == 1) {
                    if(element){
                      treedatas[n] = data.datas;
                    }
                }
              });
            }
            return;
          }
          this.resetTreeDatas(element.childs,key,type,paramsdatas,element);
      }
    }
  }
}